package org.kwisatz.proxybot.filters;

import java.io.PrintWriter;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import org.kwisatz.proxybot.Context;
import org.kwisatz.proxybot.FilterAdapter;
import org.kwisatz.proxybot.Message;
import org.kwisatz.proxybot.User;

public class Clone extends FilterAdapter
{	
	private Set<String> waitWho=new HashSet<String>();
		
	@Override
	public String handleClientLine(String line, Message message)
	{
		if("!clone".equals(message.getEndOfMsg()) &&
			Message.PRIVMSG.equals(message.getCommand()))
		{
			findClone(context, clientNotice, null);
			return null;
		}
		else
			return line;
	}
	
	@Override
	public String handleServerLine(String line, Message message)
	{
		if("JOIN".equals(message.getCommand()))
		{
			if(message.getNick().equals(context.getNickName()))
			{
				waitWho.add(message.getEndOfMsg());
			}
			else
			{
				findClone(context, clientNotice, message.getServer());
			}
		}
		/*else if(message.getCommand().equals("315"))
		{
			StringTokenizer st=new StringTokenizer(message.getCmdParam());
			st.nextToken(); //skip my nickname
			String chan=st.nextToken();
			if(waitWho.contains(chan))
			{		
				findClone(context, clientNotice, null);
				waitWho.remove(chan);
			}
		}*/
		return line;
	}
	
	private static class ChanAndNick
	{
		private String chan;
		private String nick;
		
		ChanAndNick(String chan, String nick)
		{
			this.chan = chan;
			this.nick = nick;
		}

		@Override
		public boolean equals(Object obj) {
			return nick.equals(((ChanAndNick)obj).nick);
		}
		
		@Override
		public int hashCode() {
			return nick.hashCode();
		}
		
		@Override
		public String toString() {
			return nick+" on "+chan;
		}
	}
	
	private static void findClone(Context context, PrintWriter out, String host)
	{
		Map<String, Collection<ChanAndNick>> map =
				new HashMap<String, Collection<ChanAndNick>>();
		String[] chans = context.getChannels();

		for (String chan : chans) {
			User[] us = context.getUsers(chan);

			for (User u : us) {
				String h = u.getHost();
				if (host == null || h.equals(host)) {
					Collection<ChanAndNick> l = map.get(h);
					if (l == null) {
						l = new HashSet<ChanAndNick>();
						map.put(h, l);
					}
					l.add(new ChanAndNick(chan, u.getNick()));
				}
			}
		}

		for (Entry<String, Collection<ChanAndNick>> e : map.entrySet())
		{
			Collection c = e.getValue();
			if (c.size() > 1) {
				out.println(e.getKey() + " clones: " + c);
			}
		}
	}
}
